﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TransportAnalizer_2._0.Model;

namespace TransportAnalizer_2._0.Views
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class NodeTypeView : Window
    {
        public NodeTypeView()
        {
            InitializeComponent();
        }

        public void RefreshComboBoxSelection(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = e.AddedItems[0];
            if (selectedItem != null)
            {
                var control = sender as FrameworkElement;
                var controlChilds = FindFirstChild<TextBlock>(control);
                if (controlChilds != null)
                {
                    controlChilds.Text = ((DisplayAttribute)selectedItem.GetType().GetMember(selectedItem.ToString())
                        .First().GetCustomAttributes(false).Where(x => x.GetType() == typeof(DisplayAttribute)).FirstOrDefault()).Name;
                }
            }
        }
        public static T FindFirstChild<T>(DependencyObject parent) where T : DependencyObject
        {
            // Confirm parent and childName are valid.
            if (parent == null) return null;
            T foundChild = null;
            int childrenCount = System.Windows.Media.VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindFirstChild<T>(child);
                    // If the child is found, break so we do not overwrite the found child.
                    if (foundChild != null) break;
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }
            return foundChild;
        }

    }
}
